package com.sample.springbatch.job.sample.reader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.stereotype.Component;

import java.util.LinkedList;

@Component
public class ThreadLocalReader implements ItemReader<String> {

    Logger logger = LoggerFactory.getLogger(ThreadLocalReader.class);
    ThreadLocal<Boolean> initDataFlag = null;
    private LinkedList<String> queue = new LinkedList<>();

    public synchronized void initData()
    {
        logger.info("loanSupportJob: initData");
        try
        {
            // 得到当天的业务日期
            queue.add(""+System.currentTimeMillis());
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    @Override
    public synchronized String read() throws Exception
    {
        logger.info("loanSupportJob: read");
        Boolean flag = true;
        if (initDataFlag != null && initDataFlag.get() != null)
        {
            flag = false;
        }
        if (initDataFlag == null || flag)
        {
            initData();
            initDataFlag = new ThreadLocal<>();
            initDataFlag.set(true);
        }
        logger.info("loanSupportJob: read flag:{}  initDataFlag:{}",flag,initDataFlag);
        if (queue.size() > 0)
        {
            return queue.removeFirst();
        }
        else
        {
            return null;
        }
    }


    public ThreadLocal<Boolean> getInitDataFlag()
    {
        return initDataFlag;
    }


    public void setInitDataFlag(ThreadLocal<Boolean> initDataFlag)
    {
        this.initDataFlag = initDataFlag;
    }
}


